#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动所有系统服务
"""

import subprocess
import time
import os
import sys

def start_service(command, cwd, service_name):
    """启动服务"""
    print(f"\n启动 {service_name}...")
    try:
        # 在Windows上启动后台进程
        if os.name == 'nt':
            # 使用 CREATE_NEW_CONSOLE 创建新窗口
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            process = subprocess.Popen(
                command,
                cwd=cwd,
                shell=True,
                creationflags=subprocess.CREATE_NEW_CONSOLE
            )
        else:
            # Linux/Mac
            process = subprocess.Popen(
                command,
                cwd=cwd,
                shell=True,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL
            )

        print(f"✓ {service_name} 已启动 (PID: {process.pid})")
        return process
    except Exception as e:
        print(f"✗ 启动 {service_name} 失败: {str(e)}")
        return None

def main():
    print("=" * 60)
    print("启动UCEIS系统所有服务")
    print("=" * 60)

    processes = []

    # 1. 启动AI推理服务
    ai_cmd = "python inference_server.py"
    ai_cwd = "endo_sight_uc_ai"
    ai_process = start_service(ai_cmd, ai_cwd, "AI推理服务")
    if ai_process:
        processes.append(("AI推理服务", ai_process, 5001))

    # 等待2秒
    time.sleep(2)

    # 2. 启动后端服务
    backend_cmd = "npm start"
    backend_cwd = "endo_sight_uc_server"
    backend_process = start_service(backend_cmd, backend_cwd, "后端API服务")
    if backend_process:
        processes.append(("后端API服务", backend_process, 4000))

    # 等待3秒
    time.sleep(3)

    # 3. 启动前端服务
    frontend_cmd = "npm run dev"
    frontend_cwd = "endo_sight_uc_web"
    frontend_process = start_service(frontend_cmd, frontend_cwd, "前端服务")
    if frontend_process:
        processes.append(("前端服务", frontend_process, 8101))

    print("\n" + "=" * 60)
    print("所有服务启动完成")
    print("=" * 60)

    # 等待服务完全启动
    print("\n等待服务完全启动...")
    time.sleep(5)

    # 测试服务是否正常运行
    import requests

    print("\n检查服务状态:")
    for service_name, process, port in processes:
        try:
            if service_name == "后端API服务":
                response = requests.get(f"http://localhost:{port}/api/health", timeout=3)
            elif service_name == "AI推理服务":
                response = requests.get(f"http://localhost:{port}/health", timeout=3)
            else:
                response = requests.get(f"http://localhost:{port}", timeout=3)

            if response.status_code == 200:
                print(f"✓ {service_name} 运行正常")
            else:
                print(f"✗ {service_name} 响应异常 (状态码: {response.status_code})")
        except:
            print(f"✗ {service_name} 连接失败")

    print("\n按 Ctrl+C 停止所有服务")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n\n正在停止所有服务...")
        for service_name, process, port in processes:
            try:
                process.terminate()
                print(f"✓ {service_name} 已停止")
            except:
                pass

if __name__ == "__main__":
    main()